package com.example.talkheartwalk

import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.util.Log
import android.widget.Button
import android.widget.TextView
import androidx.activity.result.ActivityResultLauncher
import androidx.activity.result.contract.ActivityResultContracts
import androidx.activity.viewModels
import androidx.lifecycle.lifecycleScope

class MainActivity : AppCompatActivity() {
    private lateinit var permissionLauncher: ActivityResultLauncher<String>
    private val sleepButton: Button by lazy { findViewById<Button>(R.id.sleep_button) }
    private val sleepLength: TextView by lazy { findViewById<TextView>(R.id.sleep_length) }
    private var startTime : Long = 0L
    private var endTime : Long = 0L

    private val viewModel: MainViewModel by viewModels()

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)


        permissionLauncher =
            registerForActivityResult(ActivityResultContracts.RequestPermission()) { result ->
                when (result) {
                    true -> {
                        viewModel.togglePassiveData(true)
                    }
                    false -> {
                        viewModel.togglePassiveData(false)
                    }
                }
            }
        sleepButton.setOnClickListener { l->
            if(sleepButton.text.equals("开始睡眠")){
                startTime = System.currentTimeMillis()
                sleepButton.text = "结束睡眠"
            } else if(sleepButton.text.equals("结束睡眠")){
                endTime = System.currentTimeMillis()
                sleepButton.text = "开始睡眠"
                var totalSecond = (endTime-startTime)/1000
                val second = totalSecond%60
                totalSecond /= 60
                val minute = totalSecond%60
                totalSecond /= 60
                val hour = totalSecond%60
                val time = String.format("睡眠时长: %d:%d:%d",hour,minute,second)
                sleepLength.text = time
            }
        }

    }

}